"""
视频处理CLI命令

提供视频扫描、分析、分类等命令。
"""

import click
import asyncio
from pathlib import Path
from typing import List, Optional

from rich.console import Console
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich.panel import Panel
from rich.text import Text

from src.bootstrap import get_service
from src.repositories import VideoRepository


console = Console()


class VideoCommand:
    """视频处理命令类"""
    
    def __init__(self):
        self.video_repo = None

    def _get_services(self):
        """获取服务实例"""
        if not self.video_repo:
            self.video_repo = get_service(VideoRepository)

    def _run_async(self, coro):
        """安全地运行异步协程"""
        try:
            # 尝试获取当前事件循环
            loop = asyncio.get_running_loop()
            # 如果已经在事件循环中，使用线程池运行
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, coro)
                return future.result()
        except RuntimeError:
            # 没有运行的事件循环，可以直接使用 asyncio.run
            return asyncio.run(coro)
    
    def register_commands(self, group):
        """注册命令到组"""
        # 使用内联函数定义Click命令
        @group.command()
        @click.argument('directory', type=click.Path(exists=True, file_okay=False, dir_okay=True))
        @click.option('--recursive', '-r', is_flag=True, help='递归扫描子目录')
        @click.option('--extensions', '-e', default='mp4,avi,mov,mkv', help='视频文件扩展名（逗号分隔）')
        @click.option('--output', '-o', type=click.Path(), help='输出结果到文件')
        def scan(directory, recursive, extensions, output):
            """扫描目录中的视频文件"""
            return self.scan_videos(directory, recursive, extensions, output)

        @group.command()
        @click.argument('video_path', type=click.Path(exists=True))
        @click.option('--detailed', '-d', is_flag=True, help='显示详细分析信息')
        def analyze(video_path, detailed):
            """分析视频文件"""
            return self.analyze_video(video_path, detailed)

        @group.command()
        @click.argument('video_path', type=click.Path(exists=True))
        @click.option('--model', '-m', default='gemini', help='AI模型选择')
        @click.option('--detailed', '-d', is_flag=True, help='显示详细分类信息')
        def classify(video_path, model, detailed):
            """AI分类视频"""
            return self.classify_video(video_path, model, detailed)

        @group.command()
        @click.option('--category', '-c', help='按分类过滤')
        @click.option('--format', '-f', help='按格式过滤')
        @click.option('--limit', '-l', default=20, help='显示数量限制')
        def list(category, format, limit):
            """列出视频"""
            return self.list_videos(category, format, limit)

        @group.command()
        @click.argument('video_id', type=int)
        def info(video_id):
            """显示视频详细信息"""
            return self.show_video_info(video_id)

        @group.command()
        def stats():
            """显示视频统计信息"""
            return self.show_video_stats()
    
    def scan_videos(self, directory, recursive, extensions, output):
        """
        扫描目录中的视频文件
        
        DIRECTORY: 要扫描的目录路径
        """
        self._get_services()
        
        console.print(f"🔍 扫描目录: [cyan]{directory}[/cyan]")
        
        # 解析扩展名
        ext_list = [ext.strip().lower() for ext in extensions.split(',')]
        console.print(f"📁 支持格式: {', '.join(ext_list)}")
        
        try:
            # 执行扫描
            result = self._run_async(self._scan_videos(directory, recursive, ext_list))
            
            if result['videos']:
                # 显示结果表格
                self._display_video_table(result['videos'])
                
                # 显示统计信息
                self._display_scan_stats(result)
                
                # 保存结果
                if output:
                    self._save_scan_result(result, output)
                    console.print(f"💾 结果已保存到: [green]{output}[/green]")
            else:
                console.print("❌ 未找到任何视频文件", style="yellow")
                
        except Exception as e:
            console.print(f"❌ 扫描失败: {e}", style="red")
    
    async def _scan_videos(self, directory, recursive, extensions):
        """执行视频扫描"""
        videos = []
        total_size = 0
        total_duration = 0

        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            BarColumn(),
            TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
            TimeElapsedColumn(),
            console=console
        ) as progress:

            task = progress.add_task("扫描视频文件...", total=None)

            # 获取所有文件
            path = Path(directory)
            if recursive:
                files = list(path.rglob('*'))
            else:
                files = list(path.iterdir())

            video_files = [f for f in files if f.is_file() and f.suffix.lower().lstrip('.') in extensions]

            if video_files:
                progress.update(task, total=len(video_files))

                for i, video_file in enumerate(video_files):
                    progress.update(task, completed=i, description=f"处理: {video_file.name}")

                    try:
                        # 基本文件信息（不依赖视频服务）
                        file_stat = video_file.stat()

                        video_data = {
                            'path': str(video_file),
                            'name': video_file.name,
                            'size': file_stat.st_size,
                            'duration': 0,  # 需要FFmpeg才能获取
                            'width': 0,     # 需要FFmpeg才能获取
                            'height': 0,    # 需要FFmpeg才能获取
                            'fps': 0,       # 需要FFmpeg才能获取
                            'format': video_file.suffix.lower().lstrip('.'),
                            'codec': ''     # 需要FFmpeg才能获取
                        }

                        videos.append(video_data)
                        total_size += video_data['size']
                        total_duration += video_data['duration']

                    except Exception as e:
                        console.print(f"⚠️  跳过文件 {video_file.name}: {e}", style="yellow")

                progress.update(task, completed=len(video_files), description="扫描完成")
        
        return {
            'videos': videos,
            'total_count': len(videos),
            'total_size': total_size,
            'total_duration': total_duration,
            'directory': directory,
            'recursive': recursive,
            'extensions': extensions
        }
    
    def _display_video_table(self, videos):
        """显示视频表格"""
        table = Table(title="扫描结果", show_header=True, header_style="bold magenta")
        table.add_column("文件名", style="cyan", no_wrap=True)
        table.add_column("大小", style="green")
        table.add_column("时长", style="blue")
        table.add_column("分辨率", style="yellow")
        table.add_column("帧率", style="white")
        table.add_column("格式", style="dim")
        
        for video in videos[:20]:  # 只显示前20个
            size_mb = video['size'] / (1024 * 1024)
            duration_str = f"{video['duration']:.1f}s" if video['duration'] else "未知"
            resolution = f"{video['width']}x{video['height']}" if video['width'] and video['height'] else "未知"
            fps_str = f"{video['fps']:.1f}" if video['fps'] else "未知"
            
            table.add_row(
                video['name'],
                f"{size_mb:.1f}MB",
                duration_str,
                resolution,
                fps_str,
                video['format']
            )
        
        if len(videos) > 20:
            table.add_row("...", "...", "...", "...", "...", f"还有 {len(videos) - 20} 个文件")
        
        console.print(table)
    
    def _display_scan_stats(self, result):
        """显示扫描统计"""
        total_size_mb = result['total_size'] / (1024 * 1024)
        total_duration_min = result['total_duration'] / 60
        
        stats_text = Text()
        stats_text.append(f"📊 统计信息\n", style="bold")
        stats_text.append(f"文件数量: {result['total_count']}\n")
        stats_text.append(f"总大小: {total_size_mb:.1f} MB\n")
        stats_text.append(f"总时长: {total_duration_min:.1f} 分钟")
        
        panel = Panel(stats_text, title="扫描统计", border_style="green")
        console.print(panel)
    
    def _save_scan_result(self, result, output_path):
        """保存扫描结果"""
        import json
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
    
    def analyze_video(self, video_path, detailed):
        """
        分析单个视频文件

        VIDEO_PATH: 视频文件路径
        """
        self._get_services()

        console.print(f"🔍 分析视频: [cyan]{video_path}[/cyan]")

        try:
            result = self._run_async(self._analyze_video(video_path, detailed))
            self._display_video_analysis(result)

        except Exception as e:
            console.print(f"❌ 分析失败: {e}", style="red")
    
    async def _analyze_video(self, video_path, save_to_db):
        """分析视频"""
        # 基本文件信息
        file_path = Path(video_path)

        # 检查文件是否存在
        if not file_path.exists():
            return {
                'path': video_path,
                'metadata': {},
                'analysis': {
                    'file_exists': False,
                    'file_readable': False,
                    'error': '文件不存在'
                }
            }

        file_stat = file_path.stat()

        # 获取真实的视频元数据
        metadata = await self._extract_video_metadata(file_path)

        # 基本分析
        analysis = {
            'file_exists': True,
            'file_readable': file_path.is_file(),
            'file_size_mb': file_stat.st_size / (1024 * 1024),
            'file_size_bytes': file_stat.st_size,
            'created_time': file_stat.st_ctime,
            'modified_time': file_stat.st_mtime
        }

        # 如果需要详细分析，添加更多信息
        if save_to_db:
            analysis.update(await self._perform_detailed_analysis(file_path, metadata))

        result = {
            'path': str(file_path),
            'metadata': metadata,
            'analysis': analysis
        }

        if save_to_db:
            # 检查视频是否已存在
            existing_video = self.video_repo.get_by_path(str(file_path))

            if existing_video:
                # 更新现有视频的元数据
                video = self.video_repo.update(
                    existing_video.id,
                    duration=metadata.get('duration'),
                    width=metadata.get('width'),
                    height=metadata.get('height'),
                    fps=metadata.get('fps'),
                    format=metadata.get('format'),
                    codec=metadata.get('codec'),
                    file_size=file_stat.st_size
                )
                result['video_id'] = video.id
                result['action'] = 'updated'
            else:
                # 创建新的视频记录
                video_data = {
                    'file_path': str(file_path),
                    'file_name': file_path.name,
                    'file_size': file_stat.st_size,
                    'duration': metadata.get('duration'),
                    'width': metadata.get('width'),
                    'height': metadata.get('height'),
                    'fps': metadata.get('fps'),
                    'format': metadata.get('format'),
                    'codec': metadata.get('codec')
                }
                video = self.video_repo.create_from_dict(video_data)
                result['video_id'] = video.id
                result['action'] = 'created'

        return result

    async def _extract_video_metadata(self, file_path):
        """提取视频元数据"""
        import subprocess
        import json

        try:
            # 使用ffprobe获取视频信息
            cmd = [
                'ffprobe',
                '-v', 'quiet',
                '-print_format', 'json',
                '-show_format',
                '-show_streams',
                str(file_path)
            ]

            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)

            if result.returncode != 0:
                console.print(f"⚠️  FFprobe 执行失败: {result.stderr}", style="yellow")
                return self._get_basic_metadata(file_path)

            data = json.loads(result.stdout)

            # 查找视频流
            video_stream = None
            for stream in data.get('streams', []):
                if stream.get('codec_type') == 'video':
                    video_stream = stream
                    break

            if not video_stream:
                console.print("⚠️  未找到视频流", style="yellow")
                return self._get_basic_metadata(file_path)

            # 提取元数据
            format_info = data.get('format', {})

            metadata = {
                'duration': float(format_info.get('duration', 0)),
                'file_size': int(format_info.get('size', 0)),
                'format': format_info.get('format_name', '').split(',')[0],
                'width': int(video_stream.get('width', 0)),
                'height': int(video_stream.get('height', 0)),
                'codec': video_stream.get('codec_name', ''),
                'fps': self._parse_fps(video_stream.get('r_frame_rate', '0/1')),
                'bit_rate': int(format_info.get('bit_rate', 0)),
                'pixel_format': video_stream.get('pix_fmt', ''),
                'profile': video_stream.get('profile', ''),
                'level': video_stream.get('level', ''),
            }

            return metadata

        except subprocess.TimeoutExpired:
            console.print("⚠️  FFprobe 超时", style="yellow")
            return self._get_basic_metadata(file_path)
        except Exception as e:
            console.print(f"⚠️  元数据提取失败: {e}", style="yellow")
            return self._get_basic_metadata(file_path)

    def _get_basic_metadata(self, file_path):
        """获取基本元数据（当FFprobe不可用时）"""
        file_stat = file_path.stat()
        return {
            'duration': 0,
            'file_size': file_stat.st_size,
            'format': file_path.suffix.lower().lstrip('.'),
            'width': 0,
            'height': 0,
            'codec': '未知',
            'fps': 0,
            'bit_rate': 0,
            'pixel_format': '未知',
            'profile': '未知',
            'level': '未知',
        }

    def _parse_fps(self, fps_str):
        """解析帧率字符串"""
        try:
            if '/' in fps_str:
                num, den = fps_str.split('/')
                return float(num) / float(den) if float(den) != 0 else 0
            return float(fps_str)
        except:
            return 0

    async def _perform_detailed_analysis(self, file_path, metadata):
        """执行详细的视频分析"""
        analysis = {}

        # 计算宽高比
        if metadata['width'] > 0 and metadata['height'] > 0:
            analysis['aspect_ratio'] = metadata['width'] / metadata['height']

            # 判断视频方向
            if analysis['aspect_ratio'] > 1.5:
                analysis['orientation'] = '横屏'
            elif analysis['aspect_ratio'] < 0.7:
                analysis['orientation'] = '竖屏'
            else:
                analysis['orientation'] = '方形'

        # 判断视频质量等级
        if metadata['height'] >= 2160:
            analysis['quality'] = '4K'
        elif metadata['height'] >= 1080:
            analysis['quality'] = '1080p'
        elif metadata['height'] >= 720:
            analysis['quality'] = '720p'
        elif metadata['height'] >= 480:
            analysis['quality'] = '480p'
        else:
            analysis['quality'] = '低清'

        # 计算比特率质量
        if metadata['bit_rate'] > 0 and metadata['duration'] > 0:
            # 每像素每秒的比特数
            pixels_per_second = metadata['width'] * metadata['height'] * metadata['fps']
            if pixels_per_second > 0:
                analysis['bits_per_pixel'] = metadata['bit_rate'] / pixels_per_second

        return analysis

    def _display_video_analysis(self, result):
        """显示视频分析结果"""
        metadata = result['metadata']
        analysis = result['analysis']

        # 检查是否有错误
        if 'error' in analysis:
            console.print(f"❌ {analysis['error']}", style="red")
            return

        # 基本信息表格
        info_table = Table(title="📹 视频信息", show_header=False)
        info_table.add_column("属性", style="cyan", no_wrap=True, width=12)
        info_table.add_column("值", style="white")

        # 文件信息
        info_table.add_row("文件路径", result['path'])
        info_table.add_row("文件大小", f"{analysis.get('file_size_mb', 0):.1f} MB")

        # 视频属性
        if metadata.get('duration', 0) > 0:
            duration = metadata['duration']
            minutes = int(duration // 60)
            seconds = int(duration % 60)
            info_table.add_row("时长", f"{minutes:02d}:{seconds:02d} ({duration:.1f}秒)")
        else:
            info_table.add_row("时长", "未知")

        if metadata.get('width', 0) > 0 and metadata.get('height', 0) > 0:
            info_table.add_row("分辨率", f"{metadata['width']}×{metadata['height']}")
        else:
            info_table.add_row("分辨率", "未知")

        if metadata.get('fps', 0) > 0:
            info_table.add_row("帧率", f"{metadata['fps']:.1f} fps")
        else:
            info_table.add_row("帧率", "未知")

        info_table.add_row("格式", metadata.get('format', '未知'))
        info_table.add_row("编码", metadata.get('codec', '未知'))

        if metadata.get('bit_rate', 0) > 0:
            bit_rate_mbps = metadata['bit_rate'] / 1_000_000
            info_table.add_row("比特率", f"{bit_rate_mbps:.1f} Mbps")

        if metadata.get('pixel_format'):
            info_table.add_row("像素格式", metadata['pixel_format'])

        console.print(info_table)

        # 分析结果
        if any(key in analysis for key in ['quality', 'orientation', 'aspect_ratio']):
            analysis_table = Table(title="📊 分析结果", show_header=False)
            analysis_table.add_column("属性", style="cyan", no_wrap=True, width=12)
            analysis_table.add_column("值", style="white")

            if 'quality' in analysis:
                analysis_table.add_row("视频质量", analysis['quality'])

            if 'orientation' in analysis:
                analysis_table.add_row("视频方向", analysis['orientation'])

            if 'aspect_ratio' in analysis:
                analysis_table.add_row("宽高比", f"{analysis['aspect_ratio']:.2f}:1")

            if 'bits_per_pixel' in analysis:
                analysis_table.add_row("像素密度", f"{analysis['bits_per_pixel']:.3f} bpp")

            console.print(analysis_table)

        # 文件状态
        status_text = Text()
        status_text.append("📋 文件状态\n", style="bold")
        status_text.append(f"✅ 文件存在: {'是' if analysis.get('file_exists') else '否'}\n")
        status_text.append(f"📖 可读取: {'是' if analysis.get('file_readable') else '否'}\n")

        if 'created_time' in analysis:
            import datetime
            created = datetime.datetime.fromtimestamp(analysis['created_time'])
            status_text.append(f"📅 创建时间: {created.strftime('%Y-%m-%d %H:%M:%S')}\n")

        if 'modified_time' in analysis:
            import datetime
            modified = datetime.datetime.fromtimestamp(analysis['modified_time'])
            status_text.append(f"🔄 修改时间: {modified.strftime('%Y-%m-%d %H:%M:%S')}\n")

        panel = Panel(status_text, title="状态信息", border_style="green")
        console.print(panel)
    
    def classify_video(self, video_path, model, detailed):
        """
        对视频进行AI分类
        
        VIDEO_PATH: 视频文件路径
        """
        self._get_services()
        
        console.print(f"🤖 AI分类视频: [cyan]{video_path}[/cyan]")
        console.print(f"🧠 使用模型: [yellow]{model}[/yellow]")
        
        try:
            result = self._run_async(self._classify_video(video_path, model, detailed))
            self._display_classification_result(result)
            
        except Exception as e:
            console.print(f"❌ 分类失败: {e}", style="red")
    
    async def _classify_video(self, video_path, model, save_to_db):
        """分类视频"""
        # 模拟分类结果（实际需要AI服务）
        file_path = Path(video_path)

        # 基于文件名进行简单分类
        filename_lower = file_path.name.lower()
        if 'product' in filename_lower or '产品' in filename_lower:
            category = 'product_showcase'
            confidence = 0.8
        elif 'model' in filename_lower or '模特' in filename_lower:
            category = 'model_wearing'
            confidence = 0.7
        elif 'usage' in filename_lower or '使用' in filename_lower:
            category = 'product_usage'
            confidence = 0.6
        else:
            category = 'uncategorized'
            confidence = 0.5

        classification = {
            'category': category,
            'confidence': confidence,
            'reasoning': f'基于文件名 "{file_path.name}" 进行分类',
            'features': ['filename_analysis'],
            'processing_time': 0.1
        }

        result = {
            'path': video_path,
            'classification': classification
        }

        if save_to_db:
            # 查找或创建视频记录
            video = self.video_repo.get_by_path(video_path)
            if not video:
                # 创建视频记录
                video_data = {
                    'file_path': video_path,
                    'file_name': file_path.name,
                    'file_size': file_path.stat().st_size
                }
                video = self.video_repo.create_from_dict(video_data)

            console.print(f"💾 已保存视频记录: {video.file_name}")
            result['video_id'] = video.id

        return result
    
    def _display_classification_result(self, result):
        """显示分类结果"""
        classification = result['classification']
        
        # 分类结果表格
        result_table = Table(title="AI分类结果", show_header=False)
        result_table.add_column("属性", style="cyan", no_wrap=True)
        result_table.add_column("值", style="white")
        
        result_table.add_row("分类", classification['category'])
        result_table.add_row("置信度", f"{classification['confidence']:.2%}")
        
        if 'reasoning' in classification:
            result_table.add_row("推理过程", classification['reasoning'])
        
        if 'features' in classification:
            features_str = ', '.join(classification['features'])
            result_table.add_row("检测特征", features_str)
        
        if 'processing_time' in classification:
            result_table.add_row("处理时间", f"{classification['processing_time']:.2f} 秒")
        
        console.print(result_table)
        
        # 置信度指示器
        confidence = classification['confidence']
        if confidence >= 0.8:
            confidence_style = "green"
            confidence_text = "高置信度"
        elif confidence >= 0.6:
            confidence_style = "yellow"
            confidence_text = "中等置信度"
        else:
            confidence_style = "red"
            confidence_text = "低置信度"
        
        console.print(f"📊 置信度评估: [{confidence_style}]{confidence_text}[/{confidence_style}]")
    
    def list_videos(self, category, format, limit):
        """列出数据库中的视频"""
        self._get_services()
        
        console.print("📋 数据库中的视频列表")
        
        try:
            # 构建过滤条件
            filters = {}
            if format:
                filters['format'] = format
            
            videos = self.video_repo.find(filters=filters, limit=limit)
            
            if category:
                # 按分类过滤
                filtered_videos = []
                for video in videos:
                    classifications = self.video_repo.find_by_category(category)
                    video_ids = [c.video_id for c in classifications]
                    if video.id in video_ids:
                        filtered_videos.append(video)
                videos = filtered_videos
            
            if videos:
                self._display_video_list(videos)
            else:
                console.print("❌ 未找到匹配的视频", style="yellow")
                
        except Exception as e:
            console.print(f"❌ 查询失败: {e}", style="red")
    
    def _display_video_list(self, videos):
        """显示视频列表"""
        table = Table(title="视频列表", show_header=True, header_style="bold magenta")
        table.add_column("ID", style="dim", no_wrap=True)
        table.add_column("文件名", style="cyan")
        table.add_column("大小", style="green")
        table.add_column("时长", style="blue")
        table.add_column("分辨率", style="yellow")
        table.add_column("状态", style="white")
        
        for video in videos:
            size_mb = video.file_size / (1024 * 1024) if video.file_size else 0
            duration_str = f"{video.duration:.1f}s" if video.duration else "未知"
            resolution = video.resolution if video.resolution else "未知"
            status = "✅ 已处理" if video.is_processed else "⏳ 待处理"
            
            table.add_row(
                str(video.id),
                video.file_name,
                f"{size_mb:.1f}MB",
                duration_str,
                resolution,
                status
            )
        
        console.print(table)
    
    def show_video_info(self, video_id):
        """显示视频详细信息"""
        self._get_services()
        
        try:
            video = self.video_repo.get_with_all_relations(video_id)
            if not video:
                console.print(f"❌ 未找到ID为 {video_id} 的视频", style="red")
                return
            
            self._display_video_info(video)
            
        except Exception as e:
            console.print(f"❌ 查询失败: {e}", style="red")
    
    def _display_video_info(self, video):
        """显示视频详细信息"""
        # 基本信息
        info_table = Table(title=f"视频信息 - {video.file_name}", show_header=False)
        info_table.add_column("属性", style="cyan", no_wrap=True)
        info_table.add_column("值", style="white")
        
        info_table.add_row("ID", str(video.id))
        info_table.add_row("文件名", video.file_name)
        info_table.add_row("文件路径", video.file_path)
        info_table.add_row("文件大小", f"{video.file_size_mb:.1f} MB")
        info_table.add_row("时长", video.duration_formatted)
        info_table.add_row("分辨率", video.resolution)
        info_table.add_row("宽高比", f"{video.aspect_ratio:.2f}" if video.aspect_ratio else "未知")
        info_table.add_row("帧率", f"{video.fps} fps" if video.fps else "未知")
        info_table.add_row("格式", video.format or "未知")
        info_table.add_row("编码", video.codec or "未知")
        info_table.add_row("处理状态", "✅ 已处理" if video.is_processed else "⏳ 待处理")
        info_table.add_row("可用状态", "✅ 可用" if video.is_available else "❌ 不可用")
        
        console.print(info_table)
        
        # 分类信息
        if video.classifications:
            classification_table = Table(title="分类信息", show_header=True, header_style="bold magenta")
            classification_table.add_column("分类", style="cyan")
            classification_table.add_column("置信度", style="green")
            classification_table.add_column("分类器", style="yellow")
            classification_table.add_column("时间", style="dim")
            
            for classification in video.classifications:
                classification_table.add_row(
                    classification.category,
                    f"{classification.confidence:.2%}",
                    classification.classifier_type,
                    classification.created_at.strftime("%Y-%m-%d %H:%M")
                )
            
            console.print(classification_table)
        
        # 元数据信息
        if video.video_metadata:
            metadata = video.video_metadata
            metadata_text = Text()
            metadata_text.append("📊 元数据信息\n", style="bold")
            metadata_text.append(f"容器格式: {metadata.container_format}\n")
            metadata_text.append(f"视频编码: {metadata.video_codec}\n")
            metadata_text.append(f"音频编码: {metadata.audio_codec}\n")
            if metadata.quality_score:
                metadata_text.append(f"质量评分: {metadata.quality_score:.2f}\n")
            if metadata.brightness:
                metadata_text.append(f"亮度: {metadata.brightness:.2f}\n")
            if metadata.contrast:
                metadata_text.append(f"对比度: {metadata.contrast:.2f}")
            
            panel = Panel(metadata_text, title="元数据", border_style="blue")
            console.print(panel)
    
    def show_video_stats(self):
        """显示视频统计信息"""
        self._get_services()
        
        console.print("📊 视频统计信息")
        
        try:
            # 获取统计信息
            processing_stats = self.video_repo.get_processing_statistics()
            format_stats = self.video_repo.get_statistics_by_format()
            resolution_stats = self.video_repo.get_statistics_by_resolution()
            category_stats = self.video_repo.get_statistics_by_category()
            
            # 处理统计
            self._display_processing_stats(processing_stats)
            
            # 格式统计
            if format_stats:
                self._display_format_stats(format_stats)
            
            # 分辨率统计
            if resolution_stats:
                self._display_resolution_stats(resolution_stats)
            
            # 分类统计
            if category_stats:
                self._display_category_stats(category_stats)
                
        except Exception as e:
            console.print(f"❌ 获取统计信息失败: {e}", style="red")
    
    def _display_processing_stats(self, stats):
        """显示处理统计"""
        stats_table = Table(title="处理统计", show_header=False)
        stats_table.add_column("指标", style="cyan", no_wrap=True)
        stats_table.add_column("数值", style="white")
        
        stats_table.add_row("总视频数", str(stats['total_videos']))
        stats_table.add_row("已处理", str(stats['processed_videos']))
        stats_table.add_row("未处理", str(stats['unprocessed_videos']))
        stats_table.add_row("不可用", str(stats['unavailable_videos']))
        stats_table.add_row("处理率", f"{stats['processing_rate']:.1%}")
        stats_table.add_row("可用率", f"{stats['availability_rate']:.1%}")
        
        console.print(stats_table)
    
    def _display_format_stats(self, stats):
        """显示格式统计"""
        format_table = Table(title="格式分布", show_header=True, header_style="bold magenta")
        format_table.add_column("格式", style="cyan")
        format_table.add_column("数量", style="green")
        format_table.add_column("总大小", style="blue")
        format_table.add_column("平均时长", style="yellow")
        
        for format_name, format_data in stats.items():
            format_table.add_row(
                format_name,
                str(format_data['count']),
                f"{format_data['total_size_mb']:.1f} MB",
                f"{format_data['avg_duration']:.1f}s"
            )
        
        console.print(format_table)
    
    def _display_resolution_stats(self, stats):
        """显示分辨率统计"""
        resolution_table = Table(title="分辨率分布", show_header=True, header_style="bold magenta")
        resolution_table.add_column("分辨率", style="cyan")
        resolution_table.add_column("数量", style="green")
        
        for resolution, count in stats.items():
            resolution_table.add_row(resolution, str(count))
        
        console.print(resolution_table)
    
    def _display_category_stats(self, stats):
        """显示分类统计"""
        category_table = Table(title="分类分布", show_header=True, header_style="bold magenta")
        category_table.add_column("分类", style="cyan")
        category_table.add_column("数量", style="green")
        category_table.add_column("平均置信度", style="blue")
        
        for category, category_data in stats.items():
            category_table.add_row(
                category,
                str(category_data['count']),
                f"{category_data['avg_confidence']:.2%}"
            )
        
        console.print(category_table)


# VideoCommand类已经通过register_commands方法注册到CLI
